package com.itheima2;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyDateUtil {
    //私有构造
    private MyDateUtil() {

    }

    //按照默认模式“yyyy-MM-dd HH:mm:ss”将日期对象格式化为字符串
    public static String dateToString(Date date) {
        //日期格式化类
        return daToString(date, null);

    }


    // 按指定的模式将日期对象格式化为字符串
    public static String daToString(Date date, String patten) {
        //校验
        if (patten == null || "".equals(patten)) {
            patten = "yyyy-MM-dd HH:mm:ss";
        }
        // 日期格式化类
        SimpleDateFormat format = new SimpleDateFormat(patten);
        String str = format.format(date);
        return str;
    }


    // 按照指定的模式将字符串解析为日期对象
    public static Date stringToDate(String dateStr, String patten) throws ParseException {
        //校检
        if (patten == null || " ".equals(patten)) {
            patten = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat format = new SimpleDateFormat(patten);
        //解析
        Date date = format.parse(dateStr);
        return date;
    }

    // 按照默认的模式“yyyy-MM-dd HH:mm:ss”将字符串解析为日期对象
    public static Date stringToDate(String dateStr) throws ParseException {
        return stringToDate(dateStr, null);
    }

    // 获取时间间隔的方法，返回的是毫秒值
    public static long millisecondBetween(Date date1, Date date2) {
        long time1 = date1.getTime();
        long time2 = date2.getTime();
        return time1>time2?time1-time2:time2-time2;
    }
    // 获取时间间隔的方法，返回的是天
    public static long daysBetween(Date date1, Date date2){
        return millisecondBetween(date1,date2)/1000/60/60/24;
    }
}
